// https://www.lintcode.com/problem/reverse-linked-list/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: n
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        ListNode new_head = null, new_tail = null;
        while (head != null) {
            if (new_head == null) {
                new_head = head;
                new_tail = new_head;
                head = head.next;
                new_tail.next = null;
            }
            else {
                ListNode _head = head.next;
                head.next = new_head;
                new_head = head;
                head = _head;

            }
        }
        return new_head;
    }
}